package com.yaodian100.mall.oauth360;

import java.security.MessageDigest;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 
 * @author aaron.chueh
 *
 */
public class Oauth360Utils{
	public String getAccessToken(String code) throws Exception{
		HttpClient client=new HttpClient();
		client.getParams().setParameter("http.protocol.content-charset","UTF-8");
		
		PostMethod method=new PostMethod("https://open.i.360.cn/oauth/token");
		method.addParameter("grant_type","authorization_code");
		method.addParameter("code",code);
		method.addParameter("client_id",Oauth360Config.CLIENT_ID);
		String clientSecret=code+"-"+Oauth360Config.CLINET_SECRET;
		clientSecret=this.encrypt(clientSecret);
		method.addParameter("client_secret",clientSecret);
		method.addParameter("redirect_uri",Oauth360Config.getEncoderCallbackUrl());
		
		client.executeMethod(method);
		JSONObject jsonObj=JSONObject.fromObject(method.getResponseBodyAsString());
		String accessToken=(String)jsonObj.get("access_token");
		
		method.releaseConnection();
		
		return accessToken;
	}
	
	public JSONObject getUserInfo(String accessToken) throws Exception{
		HttpClient client=new HttpClient();
		client.getParams().setParameter("http.protocol.content-charset","UTF-8");
		
		PostMethod method=new PostMethod("https://open.i.360.cn/api/index");
		
		method.addParameter("access_token",accessToken);
		method.addParameter("apiver","1.0");
		method.addParameter("charset","utf-8");
		method.addParameter("client_id",Oauth360Config.CLIENT_ID);
		method.addParameter("format","json");
		method.addParameter("method","User.getInfo");
		String sign="access_token="+accessToken+"apiver=1.0charset=utf-8client_id="+Oauth360Config.CLIENT_ID
					+"format=jsonmethod=User.getInfo"+Oauth360Config.CLINET_SECRET;
		sign=this.encrypt(sign);
		method.addParameter("sign",sign);
		
		client.executeMethod(method);
		JSONObject jsonObj=JSONObject.fromObject(method.getResponseBodyAsString());
		
		method.releaseConnection();
		
		return jsonObj;
	}
	
	public String encrypt(String str) {
		String result = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			result = toHexString(md.digest());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	private String toHexString(byte[] in) {
		StringBuilder hexString = new StringBuilder();
		for (int i = 0; i < in.length; i++){
			String hex = Integer.toHexString(0xFF & in[i]);
			if (hex.length() == 1){
				hexString.append('0');
			}
			hexString.append(hex);
		}
		
		return hexString.toString();
	}
}